
#pragma once
#include <map>
#include <string>
#include "iarchive.h"
#include "Character_define.h"
#include "modelrcname.h"
#include "IFile.h"


typedef map<string,CModelRCBase*> MapModelRC;

template<class T>
class CModelRCMgr
{
public:
	CModelRCMgr(const _ModelRCType& rcType) : m_eRCType(rcType)
	{
	}

	virtual CModelRCMgr<T>:: ~CModelRCMgr()
	{
		Term();
	}

	T* Get(const _ModelRCDes* pDes)
	{
		T* pT = NULL;
		string strName = CModelRCName::GetSingleton().GetModelRCName(pDes,m_eRCType);
		MapModelRC::iterator pos = m_mapModelRC.find(strName);
		if (pos != m_mapModelRC.end())
		{
			pT = (T*)pos->second;
		}
		else
		{
			const char* pPath = CModelRCName::GetSingleton().GetFullPath(strName.c_str(),m_eRCType);
			pT = Load(pPath);
			m_mapModelRC[strName] = pT;	
			if(!pT)
			{
			//	prtLOG("%s is not found!",pPath);
			}
		}	
		return pT;
	}

	T* Get(const char* pszName)
	{
		T* pT = NULL;
		MapModelRC::iterator pos = m_mapModelRC.find(pszName);
		if (pos != m_mapModelRC.end())
		{
			pT = (T*)pos->second;
		}
		else
		{
			const char* pPath = CModelRCName::GetSingleton().GetFullPath(pszName,m_eRCType);
			pT = Load(pPath);
			m_mapModelRC[pPath] = pT;	
			if(!pT)
			{
				//prtLOG("%s is not found!",pPath);
			}
		}	
		return pT;
	}

	T* Load(const char* szPathName)
	{
		T* pT = new T;
		BOOL bResult = 0;
		LOAD( szPathName, pT->Serial, &bResult);
		if (!bResult)
		{
			delete pT;
			pT = NULL;
		}
		return pT;
	}

	BOOL   Save(const char* szName,T* pT) const
	{
		BOOL bResult = 0;
		SAVE( szName, pT->Serial, &bResult);	
		return bResult;
	}
private:	
	void Term()
	{
		MapModelRC::iterator pos = m_mapModelRC.begin();
		while (!m_mapModelRC.empty())
		{
			if (pos->second)
			{
				delete pos->second;
			}

			m_mapModelRC.erase(pos++);
		}
	}

private:
	MapModelRC m_mapModelRC;
	_ModelRCType m_eRCType;
};

